<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
<div id="storage_manual_in_page" class="row-fluid" style="height: inherit;">
	<form id="storage_manual_in_carForm" class="form-horizontal" style="overflow: auto; height: calc(100% - 70px);">
        <input type="hidden" id="storage_manual_in_id" name="id" value="${info.id}">
        <input type="hidden" id="storage_manual_in_instorageDetailId" name="instorageDetailId" value="${instorageDetailId}">
		 <div class="control-group">
			<label class="control-label" >入库厂区：</label>
			<div class="controls">
				<div class="input-append span12 required">
					<select id="storage_manual_in_factoryId" name="factoryCode" onchange="factoryChange()" class="span9">
						<c:forEach items="${factoryList}" var="tp">
							<option value="${tp.id}" <c:if test="${info.factoryCode==tp.code }">selected="selected"</c:if>>${tp.factoryCodeName}</option>
						</c:forEach>
					</select>
				</div>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" >入库仓库：</label>
			<div class="controls">
				<div class="input-append span12 required">
					<select id="storage_manual_in_warehouseId" name="warehouseId" onchange="warehouseChange()" class="span9">
						<c:forEach items="${warehouseList}" var="tp">
							<option value="${tp.id}" <c:if test="${info.warehouseCode==tp.code }">selected="selected"</c:if>>
									${tp.warehouseCodeName}</option>
						</c:forEach>
					</select>
				</div>
			</div>
		</div>
        <%--<div class="control-group">
			<label class="control-label" >推荐库位：</label>
			<div class="controls">
				<div class="input-append span12">
					<textarea class="span11" id="storage_manual_in_recommendcode" readonly>${recommendCode}</textarea>
				</div>
			</div>
		</div>--%>
		<div class="control-group">
			<label class="control-label" for="storage_manual_in_shelfId" >入库库位：</label>
			<div class="controls">
				<div class="required span12" >
					<input class="span11 select2_input" type = "text" id="storage_manual_in_shelfId" name="shelfId" value="${info.shelfId}" placeholder="库位"/>
					<input type="hidden" id="storage_manual_in_wid" value="${info.shelfId}">
					<input type="hidden" id="storage_manual_in_wname" value="${info.shelfCode}">
				</div>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label" for="storage_manual_in_time" >事务时间：</label>
			<div class="controls">
				<div class="required span12" >
					<input type="text" class="form-control date-picker" id="storage_manual_in_time" name="time" value="" style="width: calc(100% - 45px);" placeholder="时间" />
				</div>
			</div>
		</div>
	</form>
	<div class="field-button" style="text-align: center;border-top: 0px;margin: 15px auto;">
		<span class="btn btn-info" onclick="storage_manual_in_saveForm();">
		   <i class="ace-icon fa fa-check bigger-110"></i>确认入库
		</span>
		<span class="btn btn-danger" onclick="layer.closeAll();">
		   <i class="icon-remove"></i>&nbsp;取消
		</span>
	</div>
</div>
<script type="text/javascript">
	let ajaxo = 0;
	//时间控件
	$(".date-picker").datetimepicker({
		format: "YYYY-MM-DD"/* ,
		autoclose : true,
	    todayHighlight : true */
	});

	$("#storage_manual_in_carForm").validate({
		rules:{
			"factoryCode":{
  				required:true,
  			},
			"warehouseId":{
				required:true,
			},
			"shelfId":{
				required:true,
			},
			"time":{
				required:true,
			}
  		},
  		messages:{
  			"factoryCode":{
  				required:"请选择厂区！",
  			},
			"warehouseId":{
				required:"请选择仓库！",
			},
			"shelfId":{
				required:"请选择入库库位！",
			},
			"time":{
				required:"请选择事务时间！",
			}
  		},
  		errorClass: "help-inline",
		errorElement: "span",
		highlight:function(element, errorClass, validClass) {
			$(element).parents('.control-group').addClass('error');
		},
		unhighlight: function(element, errorClass, validClass) {
			$(element).parents('.control-group').removeClass('error');
		}
  	});

	//确定按钮点击事件
    function storage_manual_in_saveForm() {
        if ($("#storage_manual_in_carForm").valid()){
			confirmInstorage($("#storage_manual_in_instorageDetailId").val());
		}
    }

	$("#storage_manual_in_carForm #storage_manual_in_shelfId").select2({
		placeholder: "选择库位",
		minimumInputLength: 0, //至少输入n个字符，才去加载数据
		allowClear: true, //是否允许用户清除文本信息
		delay: 250,
		formatNoMatches: "没有结果",
		formatSearching: "搜索中...",
		formatAjaxError: "加载出错啦！",
		ajax: {
			url: context_path + "/storagein/selectManualShelf.do",
			type: "POST",
			dataType: 'json',
			delay: 250,
			data: function (term, pageNo) { //在查询时向服务器端传输的数据
				term = $.trim(term);
				return {
					warehouseId:$("#storage_manual_in_warehouseId").val(),
					queryString: term, //联动查询的字符
					pageSize: 15, //一次性加载的数据条数
					pageNo: pageNo //页码
				}
			},
			results: function (data, pageNo) {
				var res = data.result;
				if (res.length > 0) { //如果没有查询到数据，将会返回空串
					var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
					return {
						results: res,
						more: more
					};
				} else {
					return {
						results: {}
					};
				}
			},
			cache: true
		}
	});

	if($("#storage_manual_in_carForm #storage_manual_in_wid").val()!=""){
		$("#storage_manual_in_carForm #storage_manual_in_shelfId").select2("data", {
			id: $("#storage_manual_in_carForm #storage_manual_in_wid").val(),
			text: $("#storage_manual_in_carForm #storage_manual_in_wname").val()
		});
	}
    
  	//入库确认
	function confirmInstorage(instoragedetail_id) {
		if (ajaxo === 1) {
			layer.alert("请等待执行完成", {icon: 3});
			return;
		}
		ajaxo = 1;
		//上月最后一天
		const lastMonthLastDay = getCurrentMonthLast();
		//提交的事务日期
		const commitTime = $("#storage_manual_in_time").val();
		//当月的第一天2020-03-01
		const monthFirstDay = getCurrentMonthFirst();
		//是否在限定时间内
		const limitTimeOrNot = compareTime(monthFirstDay + ' 00:00:00', monthFirstDay + " 08:30:00");

		//在限定时间内（当月第一天的00：00至8：30），并且选择的事务日期不是上月最后一天，则提示用户
		if (limitTimeOrNot && commitTime!=setDate(lastMonthLastDay)) {
			layer.confirm("请确认入库事务日期是否正确？", /*显示的内容*/
			{
				shift: 6,
				moveType: 1, //拖拽风格，0是默认，1是传统拖动
				title: "操作提示", /*弹出框标题*/
				icon: 3, /*消息内容前面添加图标*/
				btn: ["确定入库", "我再改一下"]/*可以有多个按钮*/
			}, function (index, layero) {
				$.ajax({
					url: context_path + "/storagein/confirmInstorage",
					type: "POST",
					data: {
						instoragedetailId : instoragedetail_id,
						factoryId : $("#storage_manual_in_factoryId").val(),
						warehouseId : $("#storage_manual_in_warehouseId").val(),
						shelfId : $("#storage_manual_in_shelfId").val(),
						time : commitTime
					},
					dataType: "JSON",
					success: function (data) {
						iTsai.form.deserialize($("#storagein_list_hiddenQueryForm"), iTsai.form.serialize($("#storagein_list_queryForm")));
						if (Boolean(data.result)) {
							layer.msg(data.msg, {icon: 1});
							//关闭当前窗口
							layer.close($queryWindow);
							//刷新列表
							$("#storagein_list_grid-table").jqGrid('setGridParam', {
								postData: {queryJsonString: JSON.stringify(iTsai.form.serialize($("#storagein_list_hiddenQueryForm")))}
							}).trigger("reloadGrid");
						} else {
							layer.alert(data.msg, {icon: 2});
							//关闭当前窗口
							layer.close($queryWindow);
						}
						ajaxo = 0;
					},
					error:function(XMLHttpRequest){
						$("#storage_confirm_doing").empty();
						alert(XMLHttpRequest.readyState);
						alert("出错啦！！！");
					}
				});
			}, function (index) {
				layer.close(index);
			});
		}else {
			$.ajax({
				url: context_path + "/storagein/confirmInstorage",
				type: "POST",
				data: {
					instoragedetailId : instoragedetail_id,
					factoryId : $("#storage_manual_in_factoryId").val(),
					warehouseId : $("#storage_manual_in_warehouseId").val(),
					shelfId : $("#storage_manual_in_shelfId").val(),
					time : commitTime
				},
				dataType: "JSON",
				success: function (data) {
					iTsai.form.deserialize($("#storagein_list_hiddenQueryForm"), iTsai.form.serialize($("#storagein_list_queryForm")));
					if (Boolean(data.result)) {
						layer.msg(data.msg, {icon: 1});
						//关闭当前窗口
						layer.close($queryWindow);
						//刷新列表
						$("#storagein_list_grid-table").jqGrid('setGridParam', {
							postData: {queryJsonString: JSON.stringify(iTsai.form.serialize($("#storagein_list_hiddenQueryForm")))}
						}).trigger("reloadGrid");
					} else {
						layer.alert(data.msg, {icon: 2});
						//关闭当前窗口
						layer.close($queryWindow);
					}
					ajaxo = 0;
				},
				error:function(XMLHttpRequest){
					$("#storage_confirm_doing").empty();
					alert(XMLHttpRequest.readyState);
					alert("出错啦！！！");
				}
			});
		}
	}

    //切换仓库获取对应仓库下的行车和推荐库位
    function warehouseChange(){
        $.ajax({
            type:"POST",
            url:context_path + "/storagein/warehouseChangeList.do",
            data:{
            	id:$("#storage_manual_in_warehouseId").val(),
				instorageDetailId:$("#storage_manual_in_instorageDetailId").val()
			},
            dataType:"json",
            success:function(data){
                $("#storage_manual_in_recommendcode").empty();
                $("#storage_manual_in_recommendcode").val(data.recommendCode);
            }
        });
	}
    
  	//切换厂区获取对应的仓库
    function factoryChange(){
        $.ajax({
            type:"POST",
            url:context_path + "/storagein/factoryChangeList.do",
            data:{
            	id:$("#storage_manual_in_factoryId").val(),
				instorageDetailId:$("#storage_manual_in_instorageDetailId").val()
			},
            dataType:"json",
            success:function(data){
            	var list = data.list;
                $("#storage_manual_in_warehouseId").empty();
                for(var i=0;i<list.length;i++){
                    $("#storage_manual_in_warehouseId").append("<option value='"+list[i].id+"'>"+list[i].code+"_"+list[i].name+"</option>");
                }
                warehouseChange();
            }
        });
	}

	function manual_today(){
		var today=new Date();
		var h=today.getFullYear();
		var m=today.getMonth()+1;
		var d=today.getDate();
		var hh=today.getHours();
		var mm=today.getMinutes();
		var ss=today.getSeconds();
		m= m<10?"0"+m:m;
		d= d<10?"0"+d:d;
		hh = hh < 10 ? "0" + hh:hh;
		mm = mm < 10 ? "0" +  mm:mm;
		ss = ss < 10 ? "0" + ss:ss;
		return h+"-"+m+"-"+d/*+" "+hh+":"+mm+":"+ss*/;
	}

	/**
	 * [isDuringDate 比较当前时间是否在指定时间段内]
	 * @author dongsir
	 * @DateTime 2019-08-21
	 * @version  1.0
	 * @param    date   [beginDateStr] [开始时间]
	 * @param    date   [endDateStr]   [结束时间]
	 * @return   Boolean
	 */
	const date = {
		isDuringDate: function (beginDateStr, endDateStr) {
			const curDate = new Date(), beginDate = new Date(beginDateStr), endDate = new Date(endDateStr);
			if (curDate >= beginDate && curDate <= endDate) {
				return true;
			}
			return false;
		}
	};


	//格式化日期
	function setDate(date){
		y=date.getFullYear();
		m=date.getMonth()+1;
		d=date.getDate();
		m=m<10?"0"+m:m;
		d=d<10?"0"+d:d;
		return y+"-"+m+"-"+d;
	}

	/**
	 * 获取当前月的第一天
	 */
	function getCurrentMonthFirst(){
		const date = new Date();
		date.setDate(1);
		return setDate(date);
	}

	/**
	 * stime 开始时间 etime 结束时间
	 */
	function compareTime (stime, etime) {
		// 转换时间格式，并转换为时间戳
		function tranDate (time) {
			return new Date(time.replace(/-/g, '/')).getTime();
		}
		// 开始时间
		const startTime = tranDate(stime);
		// 结束时间
		const endTime = tranDate(etime);
		const thisDate = new Date();
		// 获取当前时间，格式为 2018-9-10 20:08
		const currentTime = thisDate.getFullYear() + '-' + (thisDate.getMonth() + 1) + '-' + thisDate.getDate() + ' ' + thisDate.getHours()
				+ ':' + thisDate.getMinutes();
		const nowTime = tranDate(currentTime);
		// 如果当前时间处于时间段内，返回true，否则返回false
		if (nowTime < startTime || nowTime > endTime) {
			return false;
		}
		return true;
	}

	/**
	 * 获取上月的最后一天
	 */
	function getCurrentMonthLast(){
		const date = new Date();
		const nextMonthFirstDay = new Date(date.getFullYear(), date.getMonth(), 1);
		const oneDay = 1000 * 60 * 60 * 24;
		return new Date(nextMonthFirstDay-oneDay);
	}

	document.getElementById("storage_manual_in_time").value = manual_today();
</script>